/*
* 生产管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取生产工单列表接口
router.get("/list", (req, res) => {
    console.log("===========获取生产工单列表接口============");
    // 获取参数
    let req_json = toUnderlineCase(req.query)
    let {pageNum, pageSize} = req.query;
    // 判断是否为空 拼接sql
    let str_json = "where ";
    // 循环json拼接where条件
    for (const key in req_json) {
        if (req_json.hasOwnProperty(key)) {
            const element = req_json[key];
            if(element != "" && element != undefined && element != null && key != "page_num" && key != "page_size") {
                if(key == "workorder_name" || key == "product_name" || key == "client_name"){
                    // 模糊查询
                    str_json += `${key} like '%${element}%' and `
                }else{
                    // 精确查询
                    str_json += `${key} = '${element}' and `
                }
            }
        }
    }
    // 去掉最后一个and
    str_json = str_json.substring(0, str_json.length - 4);
    // 拼接分页
    if(pageNum && pageSize) {
        str_json += ` limit ${(pageNum - 1) * pageSize},${pageSize}`;
    }
    let sql = `select * from pro_workorder ${str_json}`;
    // 查询数据库
    db.query("查询生产工单列表数据", sql,(err, result) => {
        if(err) {
            res.send({
                code: 500,
                msg: "获取生产工单列表失败",
                rows: [],
            })
            return
        }
        // 查询总数
        let sql_count = `select count(*) as count from pro_workorder ${str_json}`;
        db.query("查询生产工单总数", sql_count,(err, result_count) => {

            if(err) {
                res.send({
                    code: 500,
                    msg: "获取生产工单总数失败",
                    rows: [],
                })
                return
            }
            if(result.length > 0) {
                // 变量Json数组key转成下划线第一个大写
                result = result.map(item => {
                    return toCamelCase(item)
                })
            }
            res.send({
                code: 200,
                msg: "获取生产工单列表成功",
                rows:  result,
                total: result_count[0].count
            })
        })
        
    })
    
})
router.get("/", (req, res) => {
    console.log("===========生产工单接口============");
    
    res.send({
        code: 200,
        msg: "获取生产工单列表成功",
        data: "首页",
    })
})


module.exports = router;